package com.objk.admin.security.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

/**
 * 跨域过滤器配置
 *
 * @author yuan 2018/11/14 13:54
 */
@Configuration
public class CorsFilterConfig {

    /**
     * 测试环境可以是*，正式环境必须配置对应的环境和域名
     */
    private static final String allowedOrigins = "*";

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configurationSource());
        return new CorsFilter(source);
    }

    private static CorsConfiguration configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        String[] origins = StringUtils.split(allowedOrigins, ",");
        //设置允许跨域的请求来源，防止跨域攻击
        if(origins != null && origins.length >0){
            for (String origin : origins) {
                corsConfiguration.addAllowedOrigin(origin);
            }
        }else {
            corsConfiguration.addAllowedOrigin("*");
        }
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");

        List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
        corsConfiguration.setAllowedMethods(allowedMethods);
        corsConfiguration.setAllowCredentials(false);
        corsConfiguration.setMaxAge(36000L);
        return corsConfiguration;
    }

}
